<template>
  <div class="space-y-6">
    <!-- 页面标题和操作 -->
    <div class="flex justify-between items-center">
      <h2 class="text-2xl font-bold text-gray-900">图书管理</h2>
      <el-button type="primary" @click="showAddDialog">
        <i class="fas fa-plus mr-2"></i>
        添加图书
      </el-button>
    </div>

    <!-- 搜索和筛选 -->
    <div class="bg-white rounded-lg shadow-sm p-6 border border-gray-200">
      <div class="grid grid-cols-1 md:grid-cols-5 gap-4">
        <el-input
          v-model="searchForm.title"
          placeholder="图书标题"
          clearable
        >
          <template #prefix>
            <i class="fas fa-book text-gray-400"></i>
          </template>
        </el-input>
        <el-input
          v-model="searchForm.author"
          placeholder="作者"
          clearable
        >
          <template #prefix>
            <i class="fas fa-user-edit text-gray-400"></i>
          </template>
        </el-input>
        <el-select v-model="searchForm.categoryId" placeholder="分类" clearable>
          <el-option label="全部分类" value=""></el-option>
          <el-option
            v-for="category in categories"
            :key="category.id"
            :label="category.name"
            :value="category.id"
          />
        </el-select>
        <el-select v-model="searchForm.status" placeholder="状态" clearable>
          <el-option label="全部状态" value=""></el-option>
          <el-option label="上架" value="1"></el-option>
          <el-option label="下架" value="0"></el-option>
        </el-select>
        <div class="flex space-x-2">
          <el-button type="primary" @click="handleSearch">
            <i class="fas fa-search mr-2"></i>
            搜索
          </el-button>
          <el-button @click="resetSearch">重置</el-button>
        </div>
      </div>
    </div>

    <!-- 图书列表 -->
    <div class="bg-white rounded-lg shadow-sm border border-gray-200">
      <el-table
        :data="bookList"
        v-loading="loading"
        stripe
        style="width: 100%"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column label="封面" width="100">
          <template #default="{ row }">
            <img
              :src="getImageUrl(row.cover)"
              :alt="row.title"
              class="book-cover-thumbnail"
              @error="handleImageError"
            >
          </template>
        </el-table-column>
        <el-table-column prop="title" label="标题" min-width="200" />
        <el-table-column prop="author" label="作者" width="120" />
        <el-table-column prop="publisher" label="出版社" width="120" />
        <el-table-column label="价格" width="100">
          <template #default="{ row }">
            <span class="text-red-600 font-medium">¥{{ row.price }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="stock" label="库存" width="80" />
        <el-table-column prop="sales" label="销量" width="80" />
        <el-table-column label="评分" width="100">
          <template #default="{ row }">
            <div class="flex items-center">
              <i class="fas fa-star text-yellow-400 mr-1"></i>
              <span>{{ row.rating }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="标签" width="200">
          <template #default="{ row }">
            <div class="flex flex-wrap gap-1">
              <el-tag
                v-for="tag in row.tags"
                :key="tag.id"
                size="small"
                :class="tag.tagColor || 'bg-blue-500'"
                class="text-white"
              >
                {{ tag.name }}
              </el-tag>
              <span v-if="!row.tags || row.tags.length === 0" class="text-gray-400">无标签</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="状态" width="80">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'danger'">
              {{ row.status === 1 ? '上架' : '下架' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="300" fixed="right" align="center" >
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="showEditDialog(row)">
              <i class="fas fa-edit mr-1"></i>
              编辑
            </el-button>
            <el-button
              size="small"
              :type="row.status === 1 ? 'warning' : 'success'"
              @click="toggleBookStatus(row)"
            >
              <i class="fas fa-toggle-on mr-1"></i>
              {{ row.status === 1 ? '下架' : '上架' }}
            </el-button>
            <el-button size="small" type="danger" @click="deleteBook(row)">
              <i class="fas fa-trash mr-1"></i>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="flex justify-center py-4">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 添加/编辑图书对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="800px"
      @close="resetForm"
    >
      <el-form
        ref="formRef"
        :model="bookForm"
        :rules="formRules"
        label-width="100px"
      >
        <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
          <el-form-item label="图书标题" prop="title">
            <el-input v-model="bookForm.title" />
          </el-form-item>
          <el-form-item label="作者" prop="author">
            <el-input v-model="bookForm.author" />
          </el-form-item>
          <el-form-item label="出版社" prop="publisher">
            <el-input v-model="bookForm.publisher" />
          </el-form-item>
          <el-form-item label="ISBN" prop="isbn">
            <el-input v-model="bookForm.isbn" />
          </el-form-item>
          <el-form-item label="出版日期" prop="publishDate">
            <el-date-picker
              v-model="bookForm.publishDate"
              type="date"
              placeholder="选择日期"
              style="width: 100%"
            />
          </el-form-item>
          <el-form-item label="分类" prop="categoryId">
            <el-select v-model="bookForm.categoryId" placeholder="请选择分类" style="width: 100%">
              <el-option
                v-for="category in categories"
                :key="category.id"
                :label="category.name"
                :value="category.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="售价" prop="price">
            <el-input-number v-model="bookForm.price" :precision="2" :min="0" style="width: 100%" />
          </el-form-item>
          <el-form-item label="原价" prop="originalPrice">
            <el-input-number v-model="bookForm.originalPrice" :precision="2" :min="0" style="width: 100%" />
          </el-form-item>
          <el-form-item label="页数" prop="pages">
            <el-input-number v-model="bookForm.pages" :min="1" style="width: 100%" />
          </el-form-item>
          <el-form-item label="装帧方式" prop="binding">
            <el-select v-model="bookForm.binding" placeholder="请选择装帧方式" style="width: 100%">
              <el-option label="平装" value="平装" />
              <el-option label="精装" value="精装" />
              <el-option label="软精装" value="软精装" />
            </el-select>
          </el-form-item>
          <el-form-item label="库存" prop="stock">
            <el-input-number v-model="bookForm.stock" :min="0" style="width: 100%" />
          </el-form-item>
          <el-form-item label="销量" prop="sales">
            <el-input-number v-model="bookForm.sales" :min="0" style="width: 100%" />
          </el-form-item>
          <el-form-item label="图书标签">
            <el-select
              v-model="bookForm.tagIds"
              multiple
              placeholder="请选择图书标签（最多3个）"
              style="width: 100%"
              clearable
              :multiple-limit="3"
            >
              <el-option
                v-for="tag in availableTags"
                :key="tag.id"
                :label="tag.name"
                :value="tag.id"
                :disabled="bookForm.tagIds.length >= 3 && !bookForm.tagIds.includes(tag.id)"
              >
                <span class="flex items-center">
                  <span
                    class="inline-block w-3 h-3 rounded mr-2"
                    :class="tag.tagColor || 'bg-blue-500'"
                  ></span>
                  {{ tag.name }}
                </span>
              </el-option>
            </el-select>
            <div class="text-xs text-gray-500 mt-1">
              已选择 {{ bookForm.tagIds.length }}/3 个标签
            </div>
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-switch
              v-model="bookForm.status"
              :active-value="1"
              :inactive-value="0"
              active-text="上架"
              inactive-text="下架"
            />
          </el-form-item>
        </div>
        <el-form-item label="封面图片" prop="cover">
          <div class="cover-upload-container">
            <el-upload
              ref="uploadRef"
              class="cover-uploader"
              :action="uploadAction"
              :show-file-list="false"
              :before-upload="beforeCoverUpload"
              :on-success="handleCoverSuccess"
              :on-error="handleCoverError"
              :headers="uploadHeaders"
              accept="image/*"
              drag
            >
              <div v-if="bookForm.cover" class="cover-preview">
                <img :src="getImageUrl(bookForm.cover)" alt="封面预览" class="cover-image">
                <div class="cover-overlay">
                  <i class="fas fa-edit"></i>
                  <span>点击更换</span>
                </div>
              </div>
              <div v-else class="upload-placeholder">
                <i class="fas fa-cloud-upload-alt text-4xl text-gray-400 mb-3"></i>
                <div class="text-gray-600">
                  <p class="mb-2">点击或拖拽图片到此处上传</p>
                  <p class="text-sm text-gray-500">支持 JPG、PNG、GIF 格式，文件大小不超过 2MB</p>
                </div>
              </div>
            </el-upload>
          </div>
        </el-form-item>
        <el-form-item label="图书简介" prop="description">
          <el-input
            v-model="bookForm.description"
            type="textarea"
            :rows="4"
            placeholder="请输入图书简介"
          />
        </el-form-item>
        <el-form-item label="作者简介" prop="authorBio">
          <el-input
            v-model="bookForm.authorBio"
            type="textarea"
            :rows="3"
            placeholder="请输入作者简介"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { adminAPI } from '@/api/admin.js'
import { merchantAPI } from '@/api/merchant.js'
import { useUserStore } from '@/stores/user'

const userStore = useUserStore()
const loading = ref(false)

// 根据用户角色选择API
const currentAPI = computed(() => {
  return userStore.isMerchant ? merchantAPI : adminAPI
})
const dialogVisible = ref(false)
const isEdit = ref(false)
const formRef = ref()

const searchForm = reactive({
  title: '',
  author: '',
  categoryId: '',
  status: ''
})

const bookForm = reactive({
  id: null,
  title: '',
  author: '',
  publisher: '',
  isbn: '',
  publishDate: '',
  categoryId: '',
  price: 0,
  originalPrice: 0,
  pages: 0,
  binding: '',
  cover: '',
  description: '',
  authorBio: '',
  stock: 0,
  sales: 0,
  status: 1,
  tagIds: []
})

const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

const bookList = ref([])
const categories = ref([])
const availableTags = ref([])
const uploadRef = ref()

// 上传配置
const uploadAction = ref('/api/admin/upload')
const uploadHeaders = computed(() => {
  const token = localStorage.getItem('token')
  return token ? { 'Authorization': `Bearer ${token}` } : {}
})

const dialogTitle = computed(() => isEdit.value ? '编辑图书' : '添加图书')

const formRules = {
  title: [{ required: true, message: '请输入图书标题', trigger: 'blur' }],
  author: [{ required: true, message: '请输入作者', trigger: 'blur' }],
  publisher: [{ required: true, message: '请输入出版社', trigger: 'blur' }],
  categoryId: [{ required: true, message: '请选择分类', trigger: 'change' }],
  price: [{ required: true, message: '请输入售价', trigger: 'blur' }]
}

const loadBookList = async () => {
  loading.value = true
  try {
    const params = {
      current: pagination.currentPage,
      size: pagination.pageSize,
      ...searchForm
    }

    const response = await currentAPI.value.getBookList(params)

    // 检查响应数据结构
    if (response.records) {
      // 直接从响应中获取数据（后端直接返回分页数据）
      bookList.value = response.records || []
      pagination.total = response.total || 0
    } else if (response.data && response.data.records) {
      // 如果数据在data字段中
      bookList.value = response.data.records || []
      pagination.total = response.data.total || 0
    } else {
      ElMessage.error('数据格式错误')
    }
  } catch (error) {
    console.error('加载图书列表失败:', error)
    console.error('错误详情:', error.response?.data)
    ElMessage.error('加载图书列表失败: ' + (error.response?.data?.message || error.message))
  } finally {
    loading.value = false
  }
}

const loadCategories = async () => {
  try {
    const response = await currentAPI.value.getCategoryList({})

    let categoryData = []
    if (response.records) {
      categoryData = response.records || []
    } else if (response.data && response.data.records) {
      categoryData = response.data.records || []
    }

    categories.value = [
      { id: '', name: '全部' },
      ...categoryData
    ]
  } catch (error) {
    console.error('加载分类失败:', error)
    ElMessage.error('加载分类失败')
  }
}

const loadTags = async () => {
  try {
    const response = await currentAPI.value.getAllTags()

    let tagData = []
    if (response.data) {
      tagData = response.data || []
    } else if (Array.isArray(response)) {
      tagData = response
    }

    availableTags.value = tagData
  } catch (error) {
    console.error('加载标签失败:', error)
    ElMessage.error('加载标签失败')
  }
}

const handleSearch = () => {
  pagination.currentPage = 1
  loadBookList()
}

const resetSearch = () => {
  Object.assign(searchForm, {
    title: '',
    author: '',
    categoryId: '',
    status: ''
  })
  handleSearch()
}

const showAddDialog = () => {
  isEdit.value = false
  resetForm()
  dialogVisible.value = true
}

const showEditDialog = (row) => {
  isEdit.value = true
  // 正确地将数据赋值给响应式对象
  Object.assign(bookForm, { ...row })

  // 设置标签ID列表
  if (row.tags && Array.isArray(row.tags)) {
    bookForm.tagIds = row.tags.map(tag => tag.id)
  } else {
    bookForm.tagIds = []
  }

  dialogVisible.value = true
}

const resetForm = () => {
  Object.assign(bookForm, {
    id: null,
    title: '',
    author: '',
    publisher: '',
    isbn: '',
    publishDate: '',
    categoryId: '',
    price: 0,
    originalPrice: 0,
    pages: 0,
    binding: '',
    cover: '',
    description: '',
    authorBio: '',
    stock: 0,
    sales: 0,
    status: 1,
    tagIds: []
  })
  formRef.value?.resetFields()
}

const submitForm = async () => {
  try {
    await formRef.value.validate()

    if (isEdit.value) {
      // 更新图书
      const response = await currentAPI.value.updateBook(bookForm.id, bookForm)
      if (response.code === 200) {
        ElMessage.success('图书更新成功')
        dialogVisible.value = false
        loadBookList()
      } else {
        ElMessage.error(response.message || '图书更新失败')
      }
    } else {
      // 添加图书
      const response = await currentAPI.value.createBook(bookForm)
      if (response.code === 200) {
        ElMessage.success('图书添加成功')
        dialogVisible.value = false
        loadBookList()
      } else {
        ElMessage.error(response.message || '图书添加失败')
      }
    }
  } catch (error) {
    console.error('操作失败:', error)
    ElMessage.error('操作失败：' + (error.response?.data?.message || error.message))
  }
}

const toggleBookStatus = async (row) => {
  try {
    const action = row.status === 1 ? '下架' : '上架'
    await ElMessageBox.confirm(`确定要${action}图书 "${row.title}" 吗？`, '确认操作')
    
    // 模拟API调用
    row.status = row.status === 1 ? 0 : 1
    ElMessage.success(`图书${action}成功`)
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('操作失败')
    }
  }
}

const deleteBook = async (row) => {
  try {
    await ElMessageBox.confirm(`确定要删除图书 "${row.title}" 吗？`, '确认删除', {
      type: 'warning'
    })

    await currentAPI.value.deleteBook(row.id)
    ElMessage.success('图书删除成功')
    loadBookList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error(error.message || '删除失败')
    }
  }
}

const handleSizeChange = (size) => {
  pagination.pageSize = size
  loadBookList()
}

const handleCurrentChange = (page) => {
  pagination.currentPage = page
  loadBookList()
}

// 封面上传相关方法
const beforeCoverUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt20M = file.size / 1024 / 1024 < 20

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt20M) {
    ElMessage.error('图片大小不能超过 20MB!')
    return false
  }
  return true
}

const handleCoverSuccess = (response) => {
  if (response.code === 200) {
    bookForm.cover = response.data.url
    ElMessage.success('封面上传成功')
  } else {
    ElMessage.error(response.message || '上传失败')
  }
}

const handleCoverError = (error) => {
  console.error('上传失败:', error)
  ElMessage.error('封面上传失败')
}

const getImageUrl = (url) => {
  if (!url) return ''

  // 如果是完整的URL，直接返回
  if (url.startsWith('http')) {
    return url
  }

  // 如果是上传的文件路径
  if (url.startsWith('/uploads/')) {
    return `http://localhost:8081/api${url}`
  }

  // 如果是静态资源路径
  if (url.startsWith('/assets/')) {
    return `http://localhost:8081/api${url}`
  }

  // 其他情况，添加API前缀
  return `/api${url}`
}

// 图片加载错误处理
const handleImageError = (event) => {
  console.error('图片加载失败:', event.target.src)
  // 设置默认图片
  event.target.src = ''
}

onMounted(() => {
  loadBookList()
  loadCategories()
  loadTags()
})
</script>

<style scoped>
.cover-upload-container {
  width: 100%;
  display: flex;
  justify-content: center;
}

.cover-uploader {
  width: 100%;
}

.cover-uploader :deep(.el-upload) {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: all 0.3s;
  width: 180px;
  height: 240px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f9f9f9;
}

.cover-uploader :deep(.el-upload:hover) {
  border-color: #409eff;
}

.cover-preview {
  position: relative;
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 10px;
  box-sizing: border-box;
}

.cover-image {
  max-width: 160px;
  max-height: 220px;
  object-fit: contain;
  border-radius: 4px;
}

.book-cover-thumbnail {
  width: 60px;
  height: 80px;
  object-fit: contain;
  border-radius: 4px;
  border: 1px solid #e5e7eb;
  background-color: #f9f9f9;
}

.cover-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  color: white;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: opacity 0.3s;
}

.cover-preview:hover .cover-overlay {
  opacity: 1;
}

.upload-placeholder {
  text-align: center;
  padding: 20px;
}

.upload-placeholder i {
  font-size: 48px;
  color: #c0c4cc;
  margin-bottom: 16px;
}
</style>
